package book;

import constant.Constant;
import utils.AnalyzingBook;

import java.io.IOException;

public class Library {

    //存储书籍
    public Book[] books;

    //图书馆 有效的书籍
    public int bookCount;

    private static Library library;

    private AnalyzingBook analyzingBook = new AnalyzingBook();

    public Library(){
        //读
        loadAllBook();
    }

    public static Library getLibrary() {
        if (library == null){
            library = new Library();
        }
        return library;
    }

    private void loadAllBook(){
        try {
            //1.读取文件的书籍 给到 allBook 数组当中
            Book[] allBook = analyzingBook.loadObject(Constant.All_BOOK_FILE_NAME);

            //2.给当前书架 默认分配的书籍数量为5
            books = new Book[Constant.CAPACITY];
            if(allBook == null){
                bookCount = 0;
            }else {
                int allBookLen = allBook.length;
                if(allBookLen > books.length){
                    books = new Book[allBookLen];
                }

                for (int i = 0; i < allBookLen; i++) {
                    books[i] = allBook[i];
                }

                //有效的书籍
                bookCount = allBookLen;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //存储图书到文件中
    private void storeBook() {
        try {
            analyzingBook.storeObject(books,Constant.All_BOOK_FILE_NAME);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //共用的方法
    public void searchBook() {
        System.out.println("查找图书");
    }
    public void displayBooks() {
        System.out.println("显示图书");
    }
    public void exit() {
        System.out.println("退出系统");
    }

    public void addBook(Book book) {
        System.out.println("Libary类addBook方法执行了");
    }


}
